#include "smartqa.h"
#include "ui_smartqa.h"
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMessageBox>
#include <QUrlQuery>
#include <QDateTime>
#include <QTimer>
#include <QKeyEvent>
#include <QRandomGenerator>
#include <QComboBox>

SmartQA::SmartQA(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SmartQA)
    , networkManager(new QNetworkAccessManager(this))
    , settings(new QSettings("SmartQA", "Settings"))
    , retryCount(0)
{
    ui->setupUi(this);

    // 设置模型选择下拉框
    setupModelComboBox();

    // 连接信号槽
    connect(ui->askButton, &QPushButton::clicked, this, &SmartQA::onAskButtonClicked);
    connect(ui->clearButton, &QPushButton::clicked, this, &SmartQA::onClearButtonClicked);
    connect(ui->clearHistoryButton, &QPushButton::clicked, this, &SmartQA::onClearHistoryButtonClicked);
    connect(ui->saveKeyButton, &QPushButton::clicked, this, &SmartQA::onSaveKeyButtonClicked);
    connect(ui->historyList, &QListWidget::itemClicked, this, &SmartQA::onHistoryItemClicked);
    connect(ui->modelComboBox, &QComboBox::currentTextChanged, this, &SmartQA::onModelChanged);
    connect(ui->questionInput, &QTextEdit::textChanged, [this]() {
        ui->askButton->setEnabled(!ui->questionInput->toPlainText().trimmed().isEmpty());
    });

    // 支持回车发送
    ui->questionInput->installEventFilter(this);

    // 初始化界面
    ui->askButton->setEnabled(false);
    ui->apiKeyEdit->setText(loadApiKey());

    // 加载历史记录
    QStringList history = settings->value("history").toStringList();
    for (const QString &item : history) {
        ui->historyList->addItem(item);
    }

    // 加载保存的模型选择
    QString savedModel = settings->value("selectedModel", "openai/gpt-3.5-turbo").toString();
    int modelIndex = ui->modelComboBox->findText(savedModel);
    if (modelIndex >= 0) {
        ui->modelComboBox->setCurrentIndex(modelIndex);
    }

    updateStatus("就绪 - 使用OpenRouter API");
}

SmartQA::~SmartQA()
{
    delete ui;
}

void SmartQA::setupModelComboBox()
{
    // 添加常用的OpenRouter支持的模型
    ui->modelComboBox->addItem("openai/gpt-3.5-turbo", "openai/gpt-3.5-turbo");
    ui->modelComboBox->addItem("openai/gpt-4", "openai/gpt-4");
    ui->modelComboBox->addItem("openai/gpt-4-turbo", "openai/gpt-4-turbo");
    ui->modelComboBox->addItem("anthropic/claude-2", "anthropic/claude-2");
    ui->modelComboBox->addItem("anthropic/claude-3-haiku", "anthropic/claude-3-haiku");
    ui->modelComboBox->addItem("anthropic/claude-3-sonnet", "anthropic/claude-3-sonnet");
    ui->modelComboBox->addItem("google/gemini-pro", "google/gemini-pro");
    ui->modelComboBox->addItem("meta-llama/llama-2-13b-chat", "meta-llama/llama-2-13b-chat");
    ui->modelComboBox->addItem("meta-llama/llama-2-70b-chat", "meta-llama/llama-2-70b-chat");
    ui->modelComboBox->addItem("mistralai/mistral-7b-instruct", "mistralai/mistral-7b-instruct");
    ui->modelComboBox->addItem("mistralai/mixtral-8x7b-instruct", "mistralai/mixtral-8x7b-instruct");

    // 设置下拉框宽度自适应内容
    ui->modelComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
}

void SmartQA::onModelChanged(const QString &model)
{
    settings->setValue("selectedModel", model);
    updateStatus(QString("模型已切换到: %1").arg(model));
}

void SmartQA::onAskButtonClicked()
{
    QString question = ui->questionInput->toPlainText().trimmed();
    if (!question.isEmpty()) {
        askQuestion(question);
        addToHistory(question);
        ui->questionInput->clear();
    }
}

void SmartQA::onClearButtonClicked()
{
    ui->questionInput->clear();
}

void SmartQA::onClearHistoryButtonClicked()
{
    ui->historyList->clear();
    settings->setValue("history", QStringList());
}

void SmartQA::onSaveKeyButtonClicked()
{
    saveApiKey(ui->apiKeyEdit->text());
    QMessageBox::information(this, "提示", "API Key已保存");
}

void SmartQA::onHistoryItemClicked(QListWidgetItem *item)
{
    ui->questionInput->setPlainText(item->text());
}

void SmartQA::askQuestion(const QString &question)
{
    updateStatus("正在获取答案...");

    QString apiKey = loadApiKey();
    if (apiKey.isEmpty()) {
        QMessageBox::warning(this, "错误", "请先在API设置中输入OpenRouter API Key");
        updateStatus("错误: 缺少API Key");
        return;
    }

    askQuestionWithOpenRouter(question);
}

void SmartQA::askQuestionWithOpenRouter(const QString &question)
{
    QString apiKey = loadApiKey();
    QString selectedModel = ui->modelComboBox->currentData().toString();

    QNetworkRequest request;
    request.setUrl(QUrl("https://openrouter.ai/api/v1/chat/completions"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", QString("Bearer %1").arg(apiKey).toUtf8());
    request.setRawHeader("HTTP-Referer", "https://your-app-url.com");  // 可选，但推荐
    request.setRawHeader("X-Title", "SmartQA App");  // 可选，但推荐

    // 构建请求数据
    QJsonObject requestData;
    requestData["model"] = selectedModel;

    QJsonArray messages;

    // 系统提示（可选）
    QJsonObject systemMessage;
    systemMessage["role"] = "system";
    systemMessage["content"] = "你是一个智能问答助手，请用简洁明了的语言回答用户的问题。";
    messages.append(systemMessage);

    // 用户问题
    QJsonObject userMessage;
    userMessage["role"] = "user";
    userMessage["content"] = question;
    messages.append(userMessage);

    requestData["messages"] = messages;
    requestData["stream"] = false;
    requestData["temperature"] = 0.7;
    requestData["max_tokens"] = 2048;

    QJsonDocument doc(requestData);
    QByteArray postData = doc.toJson();

    QNetworkReply *reply = networkManager->post(request, postData);
    connect(reply, &QNetworkReply::finished, this, &SmartQA::handleNetworkReply);
    connect(reply, &QNetworkReply::errorOccurred, this, &SmartQA::handleNetworkError);
}

void SmartQA::handleNetworkReply()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply) return;

    retryCount = 0;

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(response);

        if (!doc.isNull() && doc.isObject()) {
            QJsonObject obj = doc.object();

            // 检查是否有错误信息
            if (obj.contains("error")) {
                QJsonObject errorObj = obj["error"].toObject();
                QString errorMsg = errorObj.contains("message") ?
                                       errorObj["message"].toString() : "未知API错误";
                displayAnswer("API错误: " + errorMsg);
                updateStatus("API错误");
                reply->deleteLater();
                return;
            }

            if (obj.contains("choices") && obj["choices"].isArray()) {
                QJsonArray choices = obj["choices"].toArray();
                if (!choices.isEmpty()) {
                    QJsonObject firstChoice = choices.first().toObject();
                    if (firstChoice.contains("message")) {
                        QJsonObject message = firstChoice["message"].toObject();
                        if (message.contains("content")) {
                            QString answer = message["content"].toString();
                            displayAnswer(answer);
                            updateStatus("回答完成");
                            reply->deleteLater();
                            return;
                        }
                    }
                }
            }

            QString responseStr = QString::fromUtf8(response);
            displayAnswer("API响应解析失败: " + responseStr);
        } else {
            displayAnswer("无法解析API响应");
        }
    } else {
        QString errorStr = reply->errorString();
        displayAnswer("请求失败: " + errorStr);
    }

    updateStatus("就绪");
    reply->deleteLater();
}

void SmartQA::handleNetworkError()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
    if (!reply) return;

    QNetworkReply::NetworkError error = reply->error();

    retryCount++;
    if (retryCount <= maxRetries) {
        updateStatus(QString("网络错误，%1秒后重试...").arg(retryCount));
        QTimer::singleShot(1000 * retryCount, [this]() {
            QString question = ui->questionInput->toPlainText().trimmed();
            if (!question.isEmpty()) {
                askQuestion(question);
            }
        });
        reply->deleteLater();
        return;
    }

    QString errorStr;
    switch(error) {
    case QNetworkReply::ConnectionRefusedError:
        errorStr = "连接被拒绝";
        break;
    case QNetworkReply::RemoteHostClosedError:
        errorStr = "远程主机关闭连接";
        break;
    case QNetworkReply::HostNotFoundError:
        errorStr = "找不到主机";
        break;
    case QNetworkReply::TimeoutError:
        errorStr = "请求超时";
        break;
    case QNetworkReply::OperationCanceledError:
        errorStr = "操作被取消";
        break;
    case QNetworkReply::SslHandshakeFailedError:
        errorStr = "SSL握手失败";
        break;
    default:
        errorStr = "网络错误: " + QString::number(error);
        break;
    }

    displayAnswer("网络错误: " + errorStr);
    updateStatus("错误: " + errorStr);
    retryCount = 0;

    reply->deleteLater();
}

void SmartQA::displayAnswer(const QString &answer)
{
    QString formattedAnswer = QString("[%1]\n%2")
    .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))
        .arg(answer);

    ui->answerDisplay->setPlainText(formattedAnswer);
}

void SmartQA::addToHistory(const QString &question)
{
    // 添加到历史列表
    ui->historyList->addItem(question);

    // 保存到设置
    QStringList history;
    for (int i = 0; i < ui->historyList->count(); ++i) {
        history.append(ui->historyList->item(i)->text());
    }
    settings->setValue("history", history);

    // 限制历史记录数量
    if (ui->historyList->count() > 50) {
        delete ui->historyList->takeItem(0);
    }
}

void SmartQA::saveApiKey(const QString &key)
{
    settings->setValue("apiKey", key);
}

QString SmartQA::loadApiKey()
{
    return settings->value("apiKey").toString();
}

void SmartQA::updateStatus(const QString &message)
{
    ui->statusLabel->setText(message);
}

bool SmartQA::eventFilter(QObject *obj, QEvent *event)
{
    if (obj == ui->questionInput && event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
        if ((keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) &&
            keyEvent->modifiers() == Qt::NoModifier) {
            onAskButtonClicked();
            return true;
        }
    }
    return QWidget::eventFilter(obj, event);
}
